<template>
  <div>
      <!-- :model="form" ref="form" -->
    <el-form  label-width="80px" :model="spu" ref="spu">
        <el-form-item label="SPU名称">
            <el-input  placeholder="SPU名称" v-model="spu.spuName"></el-input>
        </el-form-item>
        <el-form-item label="品牌">
             <!-- v-model="model" -->
            <el-select placeholder="请选择品牌" v-model="spu.tmId">
                <el-option :label="markList.tmName" :value="markList.id" v-for="markList in TrademarkList" :key="markList.id"></el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="SPU描述">
            <el-input type="textarea" placeholder="SPU描述" :rows="4" v-model="spu.description"></el-input>
        </el-form-item>
        <el-form-item label="SPU图片">
                <el-upload action="http://39.98.123.211/admin/product/fileUpload" list-type="picture-card" 
                :file-list="ImageList" :on-preview="handlePictureCardPreview" :on-remove="handleRemove"
                :on-success='handleAvatarSuccess'
                >
                <i class="el-icon-plus"></i>
                </el-upload>
                <el-dialog :visible.sync="dialogVisible"  >
                    <img width="100%" :src="dialogImageUrl" alt="" class="avatar">
                </el-dialog>
        </el-form-item>
        <el-form-item label="销售属性">
            <el-select  :placeholder='`还有${AttrList.length}个未选择`' v-model='Att' >
                <el-option :label="List.name" :value="`${List.id}:${List.name}`" v-for="List in AttrList" :key="List.id"></el-option>
            </el-select>
            <el-button type="primary" icon="el-icon-plus" @click="Add_attrList" :disabled='AttrList.length==0'>添加销售属性</el-button>
        </el-form-item>
        <el-form-item>
            <el-table style="width: 100%" border :data="spu.spuSaleAttrList">
                <el-table-column  label="序号" width="80" type="index" align="center" ></el-table-column>
                <el-table-column  label="属性名" width="120" align="center" prop="saleAttrName">
                </el-table-column>
                <el-table-column  label="属性值名称列表" width="width" align="center" prop="spuSaleAttrValueList">
                    <template slot-scope="{row,$index}">
                        <!-- disable-transitions="false" @close="handleClose(tag) -->
                        <el-tag :key="tag.id" v-for="(tag,index) in row.spuSaleAttrValueList" closable :disable-transitions="false" @close="handleClose(row,tag,index)">{{tag.saleAttrValueName}}</el-tag>
                        <el-input class="input-new-tag"  size="small" :ref="$index"  v-if="row.inputVisible"  v-model="row.saleAttrValueName" @keyup.enter.native="handleInputConfirm(row)" @blur="handleInputConfirm(row)"></el-input>
                        <el-button  class="input-new-tag" size="small"  @click="showInput(row,$index)">添加</el-button>
                    </template>
                </el-table-column>
                <el-table-column  label="操作" width="120" align="center">
                    <template slot-scope="{row,$index}">
                        <el-button type="danger" icon="el-icon-delete" @click="RemoverowButt($index)"></el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="SaveSpuInfo" >保存</el-button>
            <el-button @click="Cancel">取消</el-button>
        </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
    name:'SpuForm',
    data() {
        return {
            Att:'',//收集销售属性的id 与属性名
            getSpu:[],  //spu基本信息
            TrademarkList:[],  //品牌数据
            ImageList:[],  //spu图片
            SaleAttrList:[], //全部销售属性
            spu:{
                category3Id:0, //三级分类的id
                description:"", //描述
                spuName:"", //spu名称
                tmId:'', //平台的id
                spuImageList:[], //收集SPU图片的信息
                spuSaleAttrList:[] //平台属性与属性值收集
            },
            dialogVisible:false, //是否显示大图
            dialogImageUrl:'',//展示的大图片
        }
    },
    computed: {
        // 计算剩余的销售属性
        AttrList(){
          let array =   this.SaleAttrList.filter((item)=>{
                return this.spu.spuSaleAttrList.every((items)=>{
                    return item.name != items.saleAttrName
                })
            })
            return array
        }
    },
    mounted() {
    },
    methods: {  
        // 获取spu基本信息
        async getSpuById(spuId){
            let result = await this.$API.spu.getSpuById(spuId);
            if (result.code==200) {
                this.getSpu = result.data
                let spu =  JSON.parse(JSON.stringify(result.data));
                this.spu = spu
            }
        },
        // 获取品牌数据
       async getTrademarkList(category3Id){
           this.spu.category3Id = category3Id
            let result = await this.$API.spu.getTrademarkList()
            if (result.code==200) {
                this.TrademarkList = result.data
            }
        },
        // 获取spu图片
        async spuImageList(spuId){
            let result = await this.$API.spu.spuImageList(spuId)
            if (result.code==200) {
                this.ImageList=result.data
                this.ImageList.forEach((item)=>{
                    this.$set(item,'name',item.imgName)
                    this.$set(item,'url',item.imgUrl)
                })
            }
        },
        //获取平台的全部销售属性（3个）
        async baseSaleAttrList(){
            let result = await this.$API.spu.baseSaleAttrList()
            if (result.code==200) {
                this.SaleAttrList = result.data
            }
        },
        // 取消按钮方法
        Cancel(){
            // 发送数据给父类
            this.$emit('getCancel',{num:0,type:'cancel'})
             // 清除之前的记录
            Object.assign(this._data,this.$options.data())
        },
        // 属性值列表名称关闭方法
        handleClose(row,tag,index){
            // tag组件的关闭按钮
            row.spuSaleAttrValueList.splice(index,1)
        },
        // 失去焦点时 属性列表输入框变成只读
        handleInputConfirm(row){
            // 判断值是不是为空值
            if (row.saleAttrValueName=='') {
                this.$message({
                    message: '警告哦，不能为空',
                    type: 'warning'
                });
                return
            }
            // 判断有没有重复的值
           let fleg =  row.spuSaleAttrValueList.some((item)=>{
                return item.saleAttrValueName == row.saleAttrValueName
            })
            // 如果为真则重复了
            if (fleg) {
                 this.$message({
                    message: '警告哦，不要输入重复值',
                    type: 'warning'
                });
                return
            }
            // input的输入框隐藏
            row.inputVisible = false
            // 需要添加的属性值
            let array = {
                saleAttrValueName:row.saleAttrValueName,
                baseSaleAttrId:row.baseSaleAttrId
            }
            row.spuSaleAttrValueList.push(array)
        },
        // 点击属性列表添加按钮显示输入框  
        showInput(row,$index){
            this.$set(row,'inputVisible',true)
            this.$set(row,'saleAttrValueName','')
            this.$nextTick(()=>{
                 this.$refs[$index].focus() //输入框获取焦点
            })
        },
        // 点击文件列表中已上传的文件时
        handlePictureCardPreview(file){
            this.dialogImageUrl = file.url;
            this.dialogVisible = true;
        },
        // 删除上传图片方法
        handleRemove(file, fileList) {
            this.ImageList = fileList
        },
        // 上传图片成功方法
        handleAvatarSuccess(res,file,fileList) {
            if (res.code==200) {
                this.ImageList.push({
                    name:file.name,
                    url:res.data,
                    'imgName':file.name,
                    'imgUrl':res.data
                })
            }
        },
        //添加属性方法
        Add_attrList(){
            let array = this.Att.split(':')
            let SaleAttrList = {
                baseSaleAttrId:array[0]-0,
                saleAttrName:array[1],
                spuSaleAttrValueList:[]
            }
            this.spu.spuSaleAttrList.push(SaleAttrList)
            this.Att=''
        },
        // 删除属性方法
        RemoverowButt($index){
            // 删除属性
            this.spu.spuSaleAttrList.splice($index,1)
        },
        // 保存选项
        async SaveSpuInfo(){
            this.ImageList.forEach((item)=>{
                delete item.url
                delete item.name
            })
            this.spu.spuImageList = this.ImageList
            this.spu.spuSaleAttrList.forEach((item)=>{
                    delete item.inputVisible
                    delete item.saleAttrValueName
            })
            let result;
            if (this.spu.id) {
                result = await this.$API.spu.updateSpuInfo(this.spu)
                 this.$emit('getCancel',{num:0,type:'updata'})
                 if (result.code == 200) {
                    this.$message({
                        message: '恭喜你，修改成功',
                        type: 'success'
                    });
                }
            }else{
                 this.$emit('getCancel',{num:0,type:'add'})
                result = await this.$API.spu.saveSpuInfo(this.spu)
                 if (result.code == 200) {
                    this.$message({
                        message: '恭喜你，添加成功',
                        type: 'success'
                    });
                }
            }
             this.spu = { 
                    category3Id:0, //三级分类的id
                    description:"", //描述
                    spuName:"", //spu名称
                    tmId:'', //平台的id
                    spuImageList:[], //收集SPU图片的信息
                    spuSaleAttrList:[] //平台属性与属性值收集
                }
             this.ImageList=[]
            
            
        }
    },
    
}
</script>

<style scoped>
  .el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
  ::v-deep .el-list-leave-active{
      transition: none !important;
  }
  ::v-deep .el-list-leave-to{
      transition: none !important;
  }
  ::v-deep .el-upload-list_item{
      transition: none !important;
  }
  ::v-deep .el-upload-list_item-thumbnail{
      object-fit: scale-down !important;
  }
  
</style>